<template>
  <el-upload
      multiple
      :limit="limitNum"
      :data="params"
      v-model:file-list="fileList"
      class="uploader"
      :headers="headers"
      :action="uploadUrl"
      list-type="picture-card"
      :on-remove="removeFile"
      :on-exceed="exceedLimit"
      :on-success="uploadSuccess"
      :on-preview="previewImg"
  >
    <el-icon class="uploader-icon"><Plus /></el-icon>
  </el-upload>
  <el-dialog v-model="isShowPreviewDialog">
    <img style="width: 100%;" :src="previewImgUrl" alt="图片预览" />
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { useApp } from '@/pinia/modules/app'
import { ElMessage } from 'element-plus'
import { uploadPictureUrl, RemoveFile } from '@/api/upload'

defineProps({
  fileList: Array,
  params: Object,
})

const emit = defineEmits(['upload-success', 'remove'])

const fileServerUrl = ref(import.meta.env.VITE_FILE_SERVER_URL)
const limitNum = ref(20)
const { authorization } = useApp()
const headers = ref({ token: authorization.token })
const uploadUrl = ref(uploadPictureUrl)
const removeFileNames = ref([])
const isShowPreviewDialog = ref(false)
const previewImgUrl = ref('')

const exceedLimit = () => {
  ElMessage.error(`最多上传${limitNum.value}张图片`)
}

const uploadSuccess = res => {
  const { code, message, data } = res
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  emit('upload-success', data.url)
}

const removeFile = async (file, files) => {
  let fileName = file.name
  if (file.response) {
    fileName = file.response.data.name
  }
  removeFileNames.value.push(fileName)
  const { code, message } = await RemoveFile({
    fileNames: removeFileNames.value
  })
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  emit('remove', files)
}

const previewImg = file => {
  let fileUrl = file.url
  if (file.response) {
    fileUrl = `${fileServerUrl.value}${file.response.data.url}`
  }
  previewImgUrl.value = fileUrl
  isShowPreviewDialog.value = true
}
</script>

<style scoped lang="scss">
.uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
  :deep(.uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 140px;
    text-align: center;
  }
}
</style>